import React, { Component } from 'react';
import {
    StyleSheet, Text, View, TouchableOpacity, Image
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import navigationSeevice from '../../../components/navigation/navigationSeevice';
import AntDesignIcon from 'react-native-vector-icons/AntDesign';
import { STORAGE_CONSTANT } from '../../../config/storage';
import StorageHelper from '../../../utils/storageHelper';

const scale = GLOBAL.SCALE;
const defaultImg = require('../../../imgs/user-head.png');
export class HeadInfo extends Component {
    constructor(props) {
        super(props);
        this.state = {
            headImg: defaultImg,// 初始化头像
        }
        this.openAlert = false; // 控制发票录入
        this.recordCount = 0;
        //图片选择器参数设置
        this.imgOptions = {
            title: '请选择图片来源',
            cancelButtonTitle: '取消',
            takePhotoButtonTitle: '拍照',
            chooseFromLibraryButtonTitle: '相册图片',
            quality: 0.1,
            storageOptions: {
                skipBackup: true,
                path: 'images'
            }
        };
        if (this.props._onScroll) {
            this.props._onScroll(this._onScroll)
        }
    }
    async componentWillMount() {
        await this._userInfo();
        this._getData();
        this._getHead();
    }

    async componentWillReceiveProps(props) {
        if (!props) return;
        await this._userInfo();
        this._getData();
        this._getHead();
    }

    _onScroll = (event) => {
        let y = parseInt(event.nativeEvent.contentOffset.y);
        let isTop = 50 - y;
        isTop = isTop < 8 ? 8 : (isTop > 50 ? 50 : isTop);
        let isOpacity = y * 0.01;
        isOpacity = isOpacity < 0 ? 0 : (isOpacity > 1 ? 1 : isOpacity);
        let isFontSize = 20 - (y * 0.1);
        isFontSize = isFontSize < 14 ? 14 : (isFontSize > 20 ? 20 : isFontSize);
        let isImg = 44 - (y * 0.1);
        isImg = isImg < 34 ? 34 : (isImg > 44 ? 44 : isImg);
        let isMargin = 20 - (y * 0.5);
        isMargin = isMargin < 5 ? 5 : (isMargin > 20 ? 20 : isMargin);
        this.topObj.setNativeProps({ style: { top: isTop * scale } });
        this.fontObj.setNativeProps({ style: { fontSize: isFontSize * scale, marginLeft: isMargin * scale } });
        this.opacityBox.setNativeProps({ style: { opacity: Math.abs(1 - isOpacity) } });
        this.imgObj.setNativeProps({ style: { height: isImg * scale, width: isImg * scale, borderRadius: isImg / 2 * scale } });
        this.imgObj2.setNativeProps({ style: { height: isImg * scale, width: isImg * scale, borderRadius: isImg / 2 * scale } });
    }

    //获取消息数据
    _getData = async () => {
        let sendData = {
            pageNo: 1,
            pageSize: 5,
            isRead: 0  // 0 未读  1 已读
        }
        let messageData = await HTTP.POST(API_GENERATE(API.INFO_LIST), sendData);
        if (messageData) {
            this.recordCount = messageData.recordCount;
            this.setState({
                ls: true
            })
        }
    }

    // 获取用户基本信息
    _userInfo = async () => {
        let account = null;
        try {
            account = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
        } catch (error) {
            console.log(error);
        }
        this.userInfo = JSON.parse(account) || {};
    }


    //获取头像
    _getHead = async () => {
        let { avatar, avatarUrl } = this.userInfo || {};
        // 获取头像接口
        if (avatarUrl) {
            this.setState({
                headImg: { uri: avatarUrl }
            })
        } else if (avatar) {
            if (this.orderly) return;
            this.orderly = true;
            let headObj = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId: avatar }, {
                rejectError: false, //是否将错误数据以reject的方式返回
                handerError: false //统一出错处理 通过toast提示
            }, 30000);
            this.orderly = false;
            this.userInfo.avatarUrl = headObj.image;
            StorageHelper.set(STORAGE_CONSTANT.USER_INFO_KEY, this.userInfo);
            if (headObj) {
                this.setState({
                    headImg: { uri: headObj.image }
                })
            } else {
                this.setState({
                    ls: true
                })
            }
        } else {
            this.setState({
                ls: true
            })
        }
    }


    //点击头像 更改
    _changeLog = () => {
        navigationSeevice.navigate('UserInfo', this.userInfo)
    }

    //头像上传图片
    _uploadImg = async (imgUrl) => {
        let uploadImgObj = {
            imgUrl,
            url: API_GENERATE(API.IMG_UPLOAD),
        }
        let responseData = await Upload.uploadImg(uploadImgObj);
        if (responseData) {
            this.setState({
                headImg: { uri: responseData.filePath }
            })
            this._changeImg(responseData.fileId, responseData.filePath);
        }
    }

    // 图片修改
    _changeImg = async (fileId, imgUrl) => {
        const requestObj = {};
        requestObj.fileId = fileId;
        let resultObj = await HTTP.POST(API_GENERATE(API.CHANGE_LOG), requestObj);
        if (resultObj) {
            StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY).then((res) => {
                let resData = JsonUtils.stringToJson(res);
                resData.avatarUrl = imgUrl;
                resData.avatar = fileId;
                StorageHelper.set(STORAGE_CONSTANT.USER_INFO_KEY, JsonUtils.jsonToString(resData));
            })
        }
        ToastUtil.showSuccess(resultObj);
    }

    render() {
        let { userName, organName } = this.userInfo || {};
        let { headImg } = this.state;
        return (
            <View style={styles.more}>
                <View style={styles.container} >
                    <View style={styles.tipBox}>
                        <TouchableOpacity style={styles.clickMore} onPress={() => { navigationSeevice.navigate('UserSetPage'); }}>
                            <Text style={{ color: '#fff', fontFamily: 'PingFangSC-Semibold', fontSize: 14 }}>设置</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.clickMore} onPress={() => { navigationSeevice.navigate('MessageIndexPage') }}>
                            {
                                this.recordCount ? (<View style={styles.number}>
                                    <Text style={styles.messageMore}>{this.recordCount > 999 ? '999+' : this.recordCount}</Text>
                                </View>) : null
                            }
                            <AntDesignIcon name='message1' style={styles.icon} />
                        </TouchableOpacity>
                    </View>
                </View>

                <View ref={(e) => { this.topObj = e; }} style={{ position: 'absolute', top: 50 * scale, width: 270 * scale }}>
                    <View style={styles.TopShow2}>
                        <TouchableOpacity ref={(e) => this.imgObj2 = e} style={styles.headImgBox} onPress={this._changeLog} activeOpacity={1}>
                            <Image ref={(e) => this.imgObj = e} style={styles.imgStyle} source={headImg} />
                        </TouchableOpacity>
                        <View style={styles.headInfo2}>
                            <View style={styles.row}>
                                <Text ref={(e) => { this.fontObj = e; }} style={styles.Name}>{userName && userName.length > 15 ? userName.substr(0, 15) : userName}</Text>
                                <Text ref={(e) => { this.opacityBox = e; }} style={styles.companyName}>{organName && organName.length > 6 ? organName.substr(0, 8) + "..." : organName}</Text>
                            </View>
                        </View>
                    </View>
                </View>
            </View >
        )
    }
}
const styles = StyleSheet.create({
    more: {
        position: 'absolute',
        width: '100%',
        zIndex: 100,
        height: 100 * scale,
    },
    container: {
        flexDirection: 'row',
        justifyContent: 'flex-end',
        backgroundColor: '#167AEA',
        alignItems: 'center',
        height: 50 * scale,
        opacity: 0.95,
    },
    companyName: {
        color: style.color.white,
        fontSize: 13 * scale,
    },
    row: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
    },
    clickMore: {
        width: 40 * scale,
        height: 30 * scale,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        position: 'relative',
        marginRight: 5 * scale
    },
    tipBox: {
        flexDirection: 'row',
        zIndex: 2,
    },
    icon: {
        fontSize: 22 * scale,
        color: '#fff'
    },
    number: {
        position: 'absolute',
        left: 18 * scale,
        top: 0,
        backgroundColor: style.color.fontRed1,
        paddingLeft: 5 * scale,
        paddingRight: 5 * scale,
        paddingTop: 1 * scale,
        paddingBottom: 1 * scale,
        zIndex: 1,
        borderRadius: 6 * scale,
        flexDirection: 'row',
        alignItems: 'center'
    },
    messageMore: {
        color: style.color.white,
        fontSize: 9 * scale,
        lineHeight: 9 * scale,
        margin: 0,
        padding: 0
    },
    TopShow2: {
        width: '100%',
        flexDirection: 'row',
        alignItems: 'center',
        overflow: 'hidden',
        marginLeft: 20 * scale,
        marginRight: 20 * scale,
        marginBottom: 20 * scale,
    },
    headBg2: {
        width: 45 * scale,
        height: 45 * scale,
        backgroundColor: '#fff',
        borderRadius: 30 * scale,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        marginRight: 20 * scale
    },
    headImgBox: {
        width: 45 * scale,
        height: 45 * scale
    },
    Name: {
        fontSize: 20 * scale,
        color: style.color.white,
        fontWeight: 'bold',
        marginTop: 8 * scale,
        marginBottom: 10 * scale,
        marginRight: 15 * scale,
        marginLeft: 20 * scale
    },
    headInfo2: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        width: 250 * scale
    },
    row2: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        width: '100%'
    },
    imgStyle: {
        width: 44 * scale,
        height: 44 * scale,
        borderRadius: 22 * scale,
        borderWidth: 3 * scale,
        borderColor: '#fff',
        marginRight: 20 * scale
    }
})